#! /usr/bin/python
# _*_ coding: utf-8 _*_

'图形化游戏'

__author__ = 'alanpo'

import maps, enums
import pygame, sys
#导入常用常量
from pygame.locals import *

#初始化游戏常量
SIZE = (22, 52)  #棋盘尺寸
LONG = 5  #初始蛇长
FOOD = 3  #盘面食物数
#初始化Pygame库
pygame.init()
#初始化游戏窗口,以一个棋子20*20计
DISPLAY = pygame.display.set_mode((SIZE[1] * 20, SIZE[0] * 20 + 20))
#设置标题
pygame.display.set_caption('Alanpo-Snake')
#定义速度变量
FPSCLOCK = pygame.time.Clock()
#初始化字体
BASICFONT = pygame.font.SysFont("FiraCode Nerd Font.TTF", 30)
#定义颜色变量
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREY = pygame.Color(150, 150, 150)
#初始化棋盘
map = maps.Maps(SIZE[0], SIZE[1])
map.set_snake(LONG).put_food(FOOD)

while True:
    #玩家操作
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_UP or event.key == K_w):
                map.do_turn(2)
            if (event.key == K_DOWN or event.key == K_s):
                map.do_turn(4)
            if (event.key == K_RIGHT or event.key == K_d):
                map.do_turn(3)
            if (event.key == K_LEFT or event.key == K_a):
                map.do_turn(1)
        else:
            pass
    #执行转向
    map.judge_to_turn()
    #执行移动
    if map.do_move():
        break

    #绘制pygame显示层
    DISPLAY.fill(BLACK)
    #绘制棋盘
    for x in range(0, SIZE[0]):
        for y in range(0, SIZE[1]):
            if map.pixel[x][y].iswhat == enums.IsWhat.Framel or map.pixel[x][
                    y].iswhat == enums.IsWhat.Framer or map.pixel[x][
                        y].iswhat == enums.IsWhat.Framexy:
                pygame.draw.rect(DISPLAY, BLACK, Rect(y * 20, x * 20, 20, 20))
            elif map.pixel[x][y].iswhat == enums.IsWhat.Block:
                pygame.draw.rect(DISPLAY, WHITE, Rect(y * 20, x * 20, 20, 20))
            elif map.pixel[x][y].iswhat == enums.IsWhat.Head or map.pixel[x][
                    y].iswhat == enums.IsWhat.Body or map.pixel[x][
                        y].iswhat == enums.IsWhat.Tail:
                pygame.draw.rect(DISPLAY, RED, Rect(y * 20, x * 20, 20, 20))
            elif map.pixel[x][y].iswhat == enums.IsWhat.Food:
                pygame.draw.rect(DISPLAY, GREY, Rect(y * 20, x * 20, 20, 20))
    #设置信息的显示颜色
    msg_Surf = BASICFONT.render(
        'score: %s,  level:  %s' % (map.score, map.level), True, WHITE)
    #设置信息显示位置
    msg_Rect = msg_Surf.get_rect()
    msg_Rect.midtop = (90, SIZE[0] * 20)
    #绑定以上设置到句柄
    DISPLAY.blit(msg_Surf, msg_Rect)
    #设置速度
    FPSCLOCK.tick(map.level + 1)
    #刷新pygame显示层
    pygame.display.flip()